<?php

namespace App\Http\Controllers\Api\Backend;

use App\Models\User;
use App\Utils\FundType;
use App\Models\UserFund;
use App\Models\Withdraw;
use App\Models\BankAccount;
use App\Services\CloundPay;
use Illuminate\Http\Request;
use App\Models\AlipayAccount;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class WithdrawController extends Controller
{
    public function index(Request $request)
    {
        $limit = $request->limit ?? 10;
        $status = $request->status ?? -1;
        $verify_status = $request->verify_status ?? -2;
        $order_no = $request->order_no;
        $startDate = $request->startDate;
        $endDate = $request->endDate ? $request->endDate . ' 23:59:59' : null;;
        $orderBy = $request->orderBy ? 'asc' : 'desc';
        $withdraws = Withdraw::when($order_no, function ($query) use ($order_no) {
            return $query->where('order_no', 'like', '%' . $order_no . '%');
        })->when($status > -1, function ($query) use ($status) {
            return $query->where('status', $status);
        })->when($verify_status > -2, function ($query) use ($verify_status) {
            return $query->where('verify_status', $verify_status);
        })->when($startDate, function ($query) use ($startDate) {
            return $query->where('created_at', '>=', $startDate);
        })->when($endDate, function ($query) use ($endDate) {
            return $query->where('created_at', '<=', $endDate);
        })->with(['user:id,username,nickname'])->orderBy('id', $orderBy)->paginate($limit);
        foreach ($withdraws as $withdraw) {
            if ($withdraw->type == 0) {
                $account = AlipayAccount::find($withdraw->account_id);
            } else {
                $account = BankAccount::find($withdraw->account_id);
            }
            $withdraw->account = $account;
        }
        return success($withdraws);
    }

    public function show($id)
    {
        $withdraw = Withdraw::with(['user'])->find($id);
        return success($withdraw);
    }

    public function update(Request $request, $id)
    {
        $data = $request->all();
        if (Withdraw::where('id', $id)->update($data)) {
            return success();
        }
        return error();
    }

    public function destroy($id)
    {
        if (Withdraw::where('id', $id)->delete()) {
            return success();
        }
        return error();
    }

    public function verify(Request $request, $id)
    {
        $verify_status = $request->verify_status;
        $remark = $request->remark ?? null;
        DB::beginTransaction();  //开启事务
        try {
            $withdraw = Withdraw::find($id);
            $user = User::find($withdraw->user_id);
            if ($verify_status == -1) {
                $priceTotal = $withdraw->price + $withdraw->handle_fee;
                $user->increment('amount', $priceTotal);
                UserFund::create([
                    'user_id' => $user->id,
                    'type' => FundType::WITHDRAW,
                    'change_amount' => $priceTotal,
                    'after_amount' => $user->amount,
                    'content' =>  '驳回原因:' . $remark,
                    'remark' => '提现驳回'
                ]);
            } else {
                if ($request->transfer_type != 0) {
                    $pay = new CloundPay;
                    $data = [
                        'order_no' => $withdraw->order_no,
                        'amount' => $withdraw->price,
                        'description' => '云联车提现'
                    ];
                    if ($request->type == 0) {
                        $account = AlipayAccount::find($user->alipay_account_id);
                        $data['channel'] = 'ali';
                        $data['recipient_account'] = $account->account;
                        $data['recipient_name'] = $account->name;
                    } elseif ($request->type == 1) {
                        $account = BankAccount::find($user->bank_account_id);
                        $data['channel'] = 'bank';
                        $data['recipient_card'] = $account->account;
                        $data['recipient_bank_code'] = $account->bank;
                        $data['recipient_name'] = $account->name;
                        $data['url'] = 'https://car-api.hyuta.com/api/cloundpay/bank-notify';
                    } elseif ($request->type == 2) {
                        $data['channel'] = 'wx';
                        $data['recipient_openid'] = $user->openid;
                    }
                    $response = $pay->withdraw($data);
                    $response = json_decode($response, true);
                    if ($response['code'] == '40011') {
                        if ($withdraw->order_no == $response['data']['order_no']) {
                            $withdraw->order_id = $response['data']['order_id'];
                            $withdraw->payment_no = $response['data']['payment_no'];
                        }
                    } else {
                        return errorMsg($response['errmsg']);
                    }
                }
                $withdraw->status = 1;
                $withdraw->transfer_type = $request->transfer_type;
                UserFund::create([
                    'user_id' => $user->id,
                    'type' => FundType::WITHDRAW,
                    'change_amount' => 0,
                    'after_amount' => $user->amount,
                    'content' => '提现成功，提现' . $withdraw->price . '元,手续费' . $withdraw->handle_fee . '元',
                    'remark' => '提现成功'
                ]);
            }
            $withdraw->verify_status = $verify_status;
            $withdraw->remark = $remark;
            $withdraw->save();
            DB::commit();
            return success();
        } catch (\Exception $e) {
            DB::rollback();
            return error($e->getMessage());
        }
    }

    public function refund(Request $request)
    {
        $orderNo = $request->order_no;
        $withdraw = Withdraw::where('order_no', $orderNo)->first();
        if(!isset($withdraw)) {
            return error('订单不存在');
        }
        $pay = new CloundPay;
        $response = $pay->refund($orderNo);
        $response = json_decode($response, true);
        if ($response['code'] == '40011') {
            return success('退款成功');
        } else {
            return error($response['errmsg']);
        }
    }
}
